from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse

from main.models import Article
from .forms import *
from .models import *
from django.contrib.auth.views import auth_login, auth_logout
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib.sites.shortcuts import get_current_site

from user.utils.encrypt_decrypt import encrypt_data, decrypt_data
from django.core.signing import TimestampSigner, BadSignature, SignatureExpired

from django.conf import settings
from django.views.generic import ListView

from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, TemplateView


@login_required
def change_head(request):
    if request.method == 'POST':
        cuif = UserInfoChangeForm(data=request.POST, files=request.FILES)
        if cuif.is_valid():
            request.user.head = cuif.cleaned_data['head']
            request.user.save()
            return redirect(reverse('user:center'))

        else:
            cuif = UserInfoChangeForm()
            return render(request, 'user/change_head.html', {'form': cuif})
    else:
        cuif = UserInfoChangeForm()
        return render(request, 'user/change_head.html', {'form': cuif})


@login_required
def center(request):
    return render(request, 'user/center.html', )


@login_required
def change_password(request):
    if request.method == 'POST':
        cgf = UserPassWordChangeForm(request.POST)
        if cgf.is_valid():
            if request.user.check_password(cgf.cleaned_data['old_password']):
                request.user.set_password(cgf.cleaned_data['password'])
                request.user.save()

                # 修改密码从新登录
                auth_logout(request)
                return redirect(reverse('user:login'))


            else:
                cgf.add_error("old_password", "原始密码不正确")
                return render(request, 'user/change_password.html', {"form": cgf})
        else:
            return render(request, 'user/change_password.html', {"form": cgf})
    else:
        cgf = UserPassWordChangeForm()
        return render(request, 'user/change_password.html', {"form": cgf})

def register(request):


    if request.method == "POST":

        rf = UserRegisterForm(request.POST)
        if rf.is_valid():
            user = rf.save(commit=False)
            user.is_active = False
            # 使用表单中用户输入的用户名，不再覆盖为email
            # user.username = user.email  # 这行代码导致了问题
            user.set_password(rf.cleaned_data['password'])

            user.save()



            # 加密用户id
            sign_util = TimestampSigner(key=settings.SECRET_KEY)

            encrypt_id = encrypt_data(f"{user.id}".encode())
            sign_id = sign_util.sign(encrypt_id)


            active_url = f"{get_current_site(request).domain}{reverse('user:active', args=(sign_id, ))}"
            active_html = f"<a href='http://{active_url}'>点我激活</a>"

            # 向注册邮箱发送激活邮件
            user.email_user("激活账户", message="", html_message=active_html)

            return redirect(reverse('user:login'))
        else:
            return render(request, 'user/register.html', {"form": rf})
    else:

        rf = UserRegisterForm()
        return render(request, 'user/register.html', {"form": rf})

def logout(request):
    auth_logout(request)
    return redirect(reverse('user:login'))
def login(request):
    if request.method == "POST":
        lf = UserLoginForm(request.POST)
        if lf.is_valid():

            user = CustomUser.objects.filter(username=lf.cleaned_data['username']).first() or CustomUser.objects.filter(email=lf.cleaned_data['username']).first()
            if user:
                if user.check_password(lf.cleaned_data['password']):
                    if user.is_active:
                        auth_login(request, user)
                        next_url = request.GET.get('next')
                        if next_url:
                            return redirect(next_url)
                        else:
                            return redirect(reverse('main:index'))
                    else:
                        lf.add_error("username", "该用户尚未激活")
                        return render(request, 'user/login.html', {"form": lf})
                else:
                    lf.add_error("password", "密码错误")
                    return render(request, 'user/login.html', {"form": lf})
            else:
                lf.add_error("username", "用户名不存在")
                return render(request, 'user/login.html', {"form": lf})
        else:

            return render(request, 'user/login.html', {"form": lf})

    else:
        lf = UserLoginForm()
        return render(request, 'user/login.html', {"form": lf})



def active(request, id):
    try:
        # 验证签名
        sign_util = TimestampSigner(key=settings.SECRET_KEY)
        encrypted_id = sign_util.unsign(id, max_age=settings.ACTIVE_EMAIL_TIME)
        # 解密用户ID
        id = decrypt_data(encrypted_id)
        # 查找用户
        user = CustomUser.objects.filter(id=id).first()
        
        if user:
            # 检查用户是否已激活
            if user.is_active:
                # 用户已激活，显示提示信息
                from django.contrib import messages
                messages.info(request, "您的账号已经激活，请直接登录。")
            else:
                # 激活用户
                user.is_active = True
                user.save()
                # 添加成功消息
                from django.contrib import messages
                messages.success(request, "账号激活成功！您现在可以登录了。")
            # 重定向到登录页面
            return redirect(reverse('user:login'))
        else:
            # 用户不存在
            return render(request, 'user/active_result.html', {
                'status': 'error',
                'message': '激活失败：用户不存在。'
            })
    except SignatureExpired:
        # 链接过期
        return render(request, 'user/active_result.html', {
            'status': 'error',
            'message': '激活失败：链接已过期，请重新注册。',
            'action_text': '重新注册',
            'action_url': reverse('user:register')
        })
    except BadSignature:
        # 链接无效
        return render(request, 'user/active_result.html', {
            'status': 'error',
            'message': '激活失败：链接无效或已被篡改。',
            'action_text': '返回登录',
            'action_url': reverse('user:login')
        })
    except Exception as e:
        # 其他错误
        return render(request, 'user/active_result.html', {
            'status': 'error',
            'message': '激活失败：发生未知错误。',
            'action_text': '返回登录',
            'action_url': reverse('user:login')
        })



# request.COOKIES  是存储在浏览器中的明码  不适合存储隐私数据  用户每次请求都会把cookie中的所有数据全部发给服务器
# 在request中获取cookie   在响应中设置cookie

# request.session 是存储在数据库中的django_session表中 存储session_key  session_data
# 关键： session_key 存储在浏览器cookie中session_id 键对应的值中  对应的值存储需要服务器通过sessionStore解析
# session的设置与获取都在请求中



class ArticleListView(ListView):
    # model = Article
    template_name = "user/article_list.html"
    def get_queryset(self):
        return Article.objects.filter(author= self.request.user )
    paginate_by = 5


class ArticleCreateView(CreateView):
    form_class = ArticleForm
    model = Article
    template_name = 'user/article_form.html'


    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)


class ArticleUpdateView(UpdateView):
    template_name = 'user/article_form.html'
    model = Article
    form_class = ArticleForm
    success_url = reverse_lazy('user:article_list')

class ArticleDeleteView(DeleteView):
    template_name = 'user/article_confirm_delete.html'
    model = Article
    success_url = reverse_lazy('user:article_list')
